import React from 'react';
import { View, Text } from '@tarojs/components';
import { AtLoadMore } from 'taro-ui';
import { shuffle } from '@/utils/common';
import './index.scss';
import ZbSeparator from '../common/Separator';

interface ISchulteGameProps {
  /**
   * 每行得方格数
   */
  columnNum: number;
  /**
   * 获取分数的回调
   */
  onChange: (data: number) => void;
  /**
   * 子节点
   */
  children?: React.ReactNode;
}

const ZbSchulteGame = (props: ISchulteGameProps) => {
  const { columnNum = 3, onChange, children } = props;

  const [item, setItem] = React.useState<number[]>([]);
  const [selectItem, setSelectItem] = React.useState<number[]>([]);
  const [step, setStep] = React.useState<number>(1);
  const [second, setSecond] = React.useState<number>(0);
  const [isResult, setIsResult] = React.useState<boolean>(false);
  const [errStep, setErrStep] = React.useState<number>();

  const timerRef = React.useRef<any>(null);

  const cols = React.useMemo<string>(() => {
    switch (columnNum) {
      case 3:
        return 'grid-cols-3';
      case 4:
        return 'grid-cols-4';
      case 5:
        return 'grid-cols-5';
      case 6:
        return 'grid-cols-6';
      case 7:
        return 'grid-cols-7';
      case 8:
        return 'grid-cols-8';
      case 9:
        return 'grid-cols-9';
      case 10:
        return 'grid-cols-10';
    }
    return '';
  }, [columnNum]);

  React.useEffect(() => {
    if (columnNum) {
      const total = columnNum * columnNum;
      const _item: number[] = [];
      for (let i = 0; i < total; i++) {
        _item.push(i + 1);
      }
      const _shuffleItem = shuffle(_item);
      setItem([..._shuffleItem]);
    }
  }, [columnNum]);

  // 渲染item之后开始倒计时
  React.useEffect(() => {
    if (item.length > 0) {
      timerRef.current = setTimeout(() => {
        const _second = second;
        setSecond(_second + 1);
      }, 1 * 1000);
    }
    return () => {
      clearInterval(timerRef.current);
    };
  }, [item, second]);

  const onTouchStart = (it: number) => {
    if (it === step) {
      if (it < item.length) {
        setStep(it + 1);
      } else {
        onChange(second);
        setIsResult(true);
        clearInterval(timerRef.current);
      }
      const _selectItem = selectItem;
      _selectItem.push(it);
      setSelectItem([..._selectItem]);
    } else {
      setErrStep(it);
    }
  };

  const onTouchEnd = () => {
    setErrStep(undefined);
  };

  if (cols === '' && item.length === 0) {
    return <AtLoadMore status="loading" />;
  }

  return (
    <View className="p-2 schulte-game">
      {/* 工具栏 */}
      <View className="grid grid-cols-4 gap-2">
        <View className="col-span-3 shadow-md rounded-md border-dashed border-4 border-light-blue-500 text-purple-600 p-1">计时：{second}秒</View>
        <View className="rounded-md shadow-md border-dashed border-4 border-light-blue-500 text-purple-600 p-1">提示：{step}</View>
      </View>
      {/* 游戏内容栏 */}
      <ZbSeparator height={20} bgColor="#F5F3FF" />
      <View className={`grid ${cols} gap-2`}>
        {item.map((it: number) => (
          <View
            key={it}
            className={`schulte-game-item shadow-md ${selectItem.findIndex((v) => v == it) > -1 ? 'bg-purple-700 text-white' : 'text-purple-600'}  ${
              it === errStep && 'bg-red-600'
            }`}
            onTouchStart={() => {
              onTouchStart(it);
            }}
            onTouchEnd={onTouchEnd}
          >
            <Text className={`schulte-game-item-text font-mono ${it === errStep && 'text-white'}`}>{it}</Text>
          </View>
        ))}
      </View>
      {/* 游戏结果展示 */}
      <ZbSeparator height={20} bgColor="#F5F3FF" />
      {isResult && (
        <View className="p-2 rounded-md shadow-md border-dashed border-4 border-red-700 ">
          <View className="text-red-800 text-center text-xl font-extrabold ">
            <Text className="bg-clip-text text-transparent bg-gradient-to-r from-green-400 to-blue-500">恭喜你取得了{second}秒的好成绩</Text>！
          </View>
          {children}
        </View>
      )}
    </View>
  );
};

export default ZbSchulteGame;
